#include <iostream>
#include <string>
#include <vector>

#include <rtmp-client.h>
#include <boost/asio.hpp>
#include <boost/system.hpp>
#include <log.h>


using namespace std;
using namespace boost::asio::ip;

using boost::asio::ip::tcp;
static char packet[2 * 1024 * 1024];

int send(void* param, const void* header, size_t len, const void* payload, size_t bytes)
{
    tcp::socket* socket = (tcp::socket*)param;

	vector<char> vec;
	vec.insert(vec.end(), (const char*)header, (const char*)header+len);
	vec.insert(vec.end(), (const char*)payload, (const char*)payload+bytes);
	return boost::asio::write(*socket, boost::asio::buffer(vec));

}

int client_onvideo(void* param, const void* video, size_t bytes, uint32_t timestamp)
{

}

int client_onaudio(void* param, const void* video, size_t bytes, uint32_t timestamp)
{
	ALOGD("audio come");
}

int client_onscript(void* param, const void* video, size_t bytes, uint32_t timestamp)
{
	ALOGD("script come");

}

void watch_live(tcp::socket& socket)
{

	// setup rtmp_client
	rtmp_client_handler_t handle;
	handle.send = send;
	rtmp_client_t* client = rtmp_client_create("live", "hello", "rtmp://127.0.0.1:6666/live", &socket, &handle);

	if (!rtmp_client_start(client, 1)) {
		//rend from server
		size_t r = 0;
		int state = 0;
		while ((r = socket.read_some(boost::asio::buffer(packet, sizeof(packet)))) > 0)
		{
			if (state!=4) {
				ALOGD("rtmp_client_getstate: %d", rtmp_client_getstate(client));
			}
			assert(0 == rtmp_client_input(client, packet, r));
		}

	}
	rtmp_client_destroy(client);
}


int main(int argc, char* argv[]) {

	boost::asio::io_context ctx;
	tcp::socket socket(ctx);

	tcp::endpoint endpoint(make_address("127.0.0.1"), 6666);
	vector<tcp::endpoint> endpoints;
	endpoints.push_back(endpoint);

	boost::system::error_code error;
	boost::asio::connect(socket, endpoints, error);

	if (!error) {
		//正常
		watch_live(socket);
		
	} else {
		cout << error.what() << endl;
	}
	
	return 0;
}
